<template>
	<view class="account-login-wrapper">
		<view class="logo">
			<image :src="pictureDomain+'logo.png'" @tap="toIndex" mode="heightFix"></image>
		</view>
		<!-- 登录 -->
		<view class="login-form" v-if="!isForgetPassword">
			<view :class="['item',errorTips==1? 'error':'']">
				<view class="account">
					<text class="input-item">{{i18n.username}}</text>
					<input type="text" @input="getInputVal" data-type="account" placeholder-class="inp-palcehoder"
						:placeholder="i18n.enterUsername">
				</view>
				<view class="error-text" v-if="errorTips==1"><text class="warning-icon">!</text>{{i18n.usernameWarn}}
				</view>
			</view>
			<view :class="['item',errorTips==2? 'error':'']">
				<view class="account">
					<text class="input-item">{{i18n.password}}</text>
					<input type="password" @input="getInputVal" data-type="password" placeholder-class="inp-palcehoder"
						:placeholder="i18n.enterPassword">
				</view>
				<view class="error-text" v-if="errorTips==2"><text class="warning-icon">!</text>{{i18n.enterPassword}}
				</view>
			</view>
			<view class="item statement">
				<view class="statement-text">
					<checkbox-group class="choose" @change="chooseChange">
						<label>
							<checkbox value="1" />{{i18n.consentOfLoginRepresentative}}
							<text @tap="toTermsOfService('serviceTerms')">{{i18n.termsOfService}}</text>{{i18n.and}}
							<text @tap="toTermsOfService('servicePolicy')">{{i18n.privacyPolicy}}</text>
						</label>
					</checkbox-group>

				</view>
			</view>
			<view class="operate">
				<view :class="(i18n.registeredUsername.length>3?'forgot-passwordEn':'forgot-password')"
					@tap="forgotPassword">{{i18n.changePassword}}></view>
				<view :class="(i18n.registeredUsername.length>3?'to-registerEn':'to-register')" @tap="toRegitser">
					{{i18n.notUsername}}<text>{{i18n.registeredUsername}}></text>
				</view>
			</view>
		</view>
		<!-- 修改密码 -->
		<view class="login-form" v-if="isForgetPassword">
			<view class="form-title">{{i18n.changePassword}}</view>
			<view :class="['item',errorTips ? 'error':'']" v-if="!nextBtn">
				<view class="account">
					<text class="input-item">{{i18n.phoneNumber}}</text>
					<input type="number" v-model="principal" placeholder-class="inp-palcehoder"
						:placeholder="i18n.enterPhone" maxlength="11">
				</view>
				<view class="error-text" v-if="errorTips==1"><text class="warning-icon">!</text>{{i18n.phoneWarn}}
				</view>
				<view class="error-text" v-if="!principal && errorTips==8"><text
						class="warning-icon">!</text>{{i18n.enterPhone}}</view>
			</view>
			<!-- 验证码 -->
			<view :class="['item',errorTips ? 'error':'']" v-if="!nextBtn">
				<view class="account">
					<text class="input-item">{{i18n.verificationCode}}</text>
					<input type="text" class="int-yzm" maxlength="6" v-model="validCode"
						placeholder-class="inp-palcehoder" :placeholder="i18n.enterCode">
					<text class="input-btn" @tap="getCode" v-if="show">{{i18n.getCode}}</text>
					<text class="input-btn" v-if="!show">{{count}} s</text>
				</view>
				<view class="error-text" v-if="errorTips==3"><text class="warning-icon">!</text>{{i18n.enterCode}}
				</view>
				<view class="error-text" v-if="errorTips==6"><text class="warning-icon">!</text>{{i18n.enterCodeFirst}}
				</view>
			</view>
			<!-- 新密码 -->
			<view :class="['item',errorTips ? 'error':'']" v-if="nextBtn">
				<view class="account">
					<text class="input-item">{{i18n.newPassword}}</text>
					<input type="password" @input="getPassInputVal" data-type="0" :value="newPassWord"
						placeholder-class="inp-palcehoder" :placeholder="i18n.enterNew">
				</view>
				<view class="error-text" v-if="errorTips==4"><text class="warning-icon">!</text>{{i18n.enterNew}}</view>
				<view class="error-text" v-if="errorTips==9"><text
						class="warning-icon">!</text>{{i18n.passwordVerification}}</view>
				<view class="error-text" v-if="errorTips==10"><text
						class="warning-icon">!</text>{{i18n.enterNewPasswordTips}}</view>
			</view>
			<!-- 新密码 -->
			<view :class="['item',errorTips ? 'error':'']" v-if="nextBtn">
				<view class="account">
					<text class="input-item">{{i18n.confirmNew}}</text>
					<input type="password" @input="getPassInputVal" data-type="1" :value="comNewPassWord"
						placeholder-class="inp-palcehoder" :placeholder="i18n.enterNewAgain">
				</view>
				<view class="error-text" v-if="errorTips==5"><text class="warning-icon">!</text>{{i18n.enterNewAgain}}
				</view>
				<view class="error-text" v-if="errorTips==7 && !identical"><text
						class="warning-icon">!</text>{{i18n.comparedPassword}}</view>
			</view>
		</view>
		<view v-if="!isForgetPassword">
			<button class="authorized-btn" @tap="login">{{i18n.login}}</button>
			<button class="to-idx-btn" @tap="toIndex">{{i18n.backHomepage}}</button>
		</view>
		<view v-if="isForgetPassword && !nextBtn">
			<button class="authorized-btn" @tap="nextStep">{{i18n.nextStep}}</button>
			<button class="to-idx-btn" @tap="goBack" v-if="!isPersonalCenter">{{i18n.BackLogin}}</button>
		</view>
		<view v-if="isForgetPassword && nextBtn">
			<button class="authorized-btn" @tap="changePassWord">{{i18n.confirmChanges}}</button>
			<button class="to-idx-btn" @tap="goBack" v-if="!isPersonalCenter">{{i18n.BackLogin}}</button>
		</view>
	</view>
</template>

<script>
	var http = require("@/utils/http");
	var util = require('@/utils/util.js');
	var config = require("@/utils/config.js");
	import {
		AppType
	} from '@/utils/constant.js'
	export default {
		data() {
			return {
				pictureDomain: config.pictureDomain,
				principal: '',
				credentials: '',
				isForgetPassword: false, //是否修改密码
				isPersonalCenter: false, //是否从个人中心页面跳转过来
				show: true, //获取验证码按钮
				// 验证码相关
				validCode: '', //验证码
				count: '',
				timer: null,
				nextBtn: false, //修改密码下一步
				newPassWord: '', //新密码
				comNewPassWord: '', //确认新密码
				checkRegisterSmsFlag: '', // 校验验证码成功的标识
				errorTips: 0, //错误提示
				identical: Boolean, //是否一致
				uniLoginLogoImg: '', // Logo
				code: '',
				isChoose: false
			};
		},

		components: {},
		props: {},
		computed: {
			i18n() {
				return this.$t('index')
			}
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			if (options.isForgetPassword) {
				this.isForgetPassword = options.isForgetPassword
				uni.setNavigationBarTitle({
					title: this.i18n.changePassword
				})
			}
			if (options.isPersonalCenter) {
				this.isPersonalCenter = options.isPersonalCenter
				uni.setNavigationBarTitle({
					title: this.i18n.changePassword
				})
			} else {
				//头部导航标题
				uni.setNavigationBarTitle({
					title: this.i18n.userLogin
				})
			}
			if (!uni.getStorageSync('code') && uni.getStorageSync('appType') === AppType.MP) {
				const code = util.getUrlKey('code')
				this.code = util.getUrlKey('code')
				uni.setStorageSync('code', code)
			}

		},

		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {
			//头部导航标题
			uni.setNavigationBarTitle({
				title: this.isForgetPassword ? this.i18n.changePassword : this.i18n.userLogin
			});

			var uniLoginLogoImg = uni.getStorageSync("uniLoginLogoImg");
			// console.log(uniLoginLogoImg)
			if (uniLoginLogoImg) {
				this.uniLoginLogoImg = uniLoginLogoImg
			}
		},

		methods: {
			chooseChange(e) {
				if (e.detail.value && e.detail.value.length > 0 && e.detail.value[0] == 1) {
					this.isChoose = true;
				}else{
					this.isChoose = false;
				}
			},
			/**
			 * 输入框的值
			 */
			getInputVal: function(e) {
				const type = e.currentTarget.dataset.type;
				// 手机号码
				if (type == 'account') {
					this.setData({
						principal: e.detail.value
					});
				} else if (type == 'password') {
					this.setData({
						credentials: e.detail.value
					});
				}
			},

			getPassInputVal: function(e) {
				var type = e.currentTarget.dataset.type
				if (type == 0) {
					this.newPassWord = e.detail.value;
					// 密码由字母加数字或符号至少两种以上字符组成6-20位半角字符，区分大小写
					var reg = new RegExp("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\\W]{6,20}$");
					let result = reg.test(this.newPassWord);
					if (!result) {
						this.setData({
							errorTips: 9,
						})
						return
					} else {
						this.setData({
							errorTips: 0,
						})
					}
				} else if (type == 1) {
					if (this.errorTips == 9) {
						this.setData({
							errorTips: 10,
						})
						return
					}
					this.comNewPassWord = e.detail.value
					setTimeout(() => {
						if (this.errorTips == 9 || this.errorTips == 10) {
							return
						}
						if (this.comNewPassWord && this.newPassWord && (this.comNewPassWord != this
								.newPassWord)) {
							this.setData({
								errorTips: 7,
								identical: false
							})
						} else if (!this.comNewPassWord) {
							this.errorTips = 5
						} else {
							this.setData({
								errorTips: 0,
								identical: true
							})
						}
					}, 1000)
				}
			},

			/**
			 * 登录
			 */
			login() {
				// #ifdef H5
				var ua = navigator.userAgent.toLowerCase();
				var data = {
					appType: ua.search(/MicroMessenger/i) > -1 ? AppType.MP : AppType.H5,
					principal: ua.search(/MicroMessenger/i) > -1 ? this.principal + ':' + uni.getStorageSync('code') :
						this.principal,
					credentials: this.credentials,
					loginType: 0, //账号登录
				}
				// #endif
				// #ifdef APP-PLUS
				var data = {
					appType: uni.getStorageSync('appType'),
					principal: this.principal,
					credentials: this.credentials,
					loginType: 0, //账号登录
				}
				// #endif
				if (!this.isChoose) {
					uni.showToast({
						title: '请先勾选用户服务条款与隐私政策',
						duration: 2000,
						icon: "none"
					});
					return;
				}
				if (this.principal.length == 0) {
					this.setData({
						errorTips: 1
					})
					return
				} else if (this.credentials.length == 0) {
					this.setData({
						errorTips: 2
					})
					return
				} else {
					this.setData({
						errorTips: 0
					})
					// #ifdef H5 || APP-PLUS
					var params = {
						url: "/login",
						method: "post",
						data: data,
						callBack: res => {
							http.loginSuccess(res, () => {
								uni.showToast({
									title: this.i18n.loginSuccessful,
									icon: 'none',
									complete: () => {
										this.routeUrlAfterLoginSuccessed()
									}
								})
							})
						}
					}
					http.request(params)
					// #endif

					// #ifdef MP-WEIXIN
					debugger
					wx.login({
						success: (res) => {
							debugger
							var params = {
								url: "/login",
								method: "post",
								data: {
									appType: 1,
									credentials: this.credentials,
									loginType: 0,
									principal: this.principal + ':' + res.code
								},
								callBack: result => {
									http.loginSuccess(result)
									this.routeUrlAfterLoginSuccessed()
								},
							}
							http.request(params)
						},
					})
					// #endif
				}
			},

			/**
			 * 登录成功后跳转
			 */
			routeUrlAfterLoginSuccessed() {
				const routeUrlAfterLogin = uni.getStorageSync('routeUrlAfterLogin')
				if (routeUrlAfterLogin) {
					this.$Router.replaceAll(routeUrlAfterLogin)
				} else {
					this.$Router.pushTab('/pages/index/index')
				}
			},


			/**
			 * 修改密码（登录页修改密码按钮）
			 */
			forgotPassword() {
				this.setData({
					isForgetPassword: true,
					principal: '',
					credentials: ''
				})

				uni.setNavigationBarTitle({
					title: this.i18n.changePassword
				});
			},


			/**
			 * 获取验证码
			 */
			getCode: function() {
				if (!this.principal.trim()) {
					this.errorTips = 8
					return
				}
				// 判断手机号码格式是否正确
				if (!util.checkPhoneNumber(this.principal)) {
					this.setData({
						errorTips: 1
					})
					return
				}
				var params = {
					url: "/sms/sendUpdatePwdCode",
					method: "POST",
					data: {
						mobile: this.principal,
					},
					callBack: res => {
						const timeCount = 60;
						if (!this.timer) {
							this.count = timeCount
							this.show = false;
							this.timer = setInterval(() => {
								if (this.count > 0 && this.count <= timeCount) {
									this.count--;
								} else {
									clearInterval(this.timer);
									this.timer = null
									this.show = true
								}
							}, 1000)
						}
					}
				};
				http.request(params);
			},
			/**
			 *  修改密码（下一步）
			 */
			nextStep() {
				if (!this.principal.trim()) {
					this.errorTips = 8
					return
				}
				if (!util.checkPhoneNumber(this.principal)) {
					this.setData({
						errorTips: 1
					})
					return
				}
				if (!this.validCode.trim()) { // 请输入验证码
					this.setData({
						errorTips: 3
					})
					return
				}
				// 校验验证码
				var params = {
					url: "/user/checkUpdatePwdSms",
					method: "put",
					data: {
						mobile: this.principal,
						validCode: this.validCode
					},
					callBack: res => {
						this.setData({
							checkRegisterSmsFlag: res,
							nextBtn: !this.nextBtn
						})
					}
				};
				http.request(params);
			},

			/**
			 * 修改密码(确认按钮)
			 */
			changePassWord() {

				if (this.errorTips == 9 || this.errorTips == 10) {
					return
				}
				if (!this.newPassWord) {
					this.setData({
						errorTips: 4
					})
					return
				}
				if (!this.newPassWord.trim()) {
					this.setData({
						errorTips: 10
					})
					return
				}
				if (!this.comNewPassWord) {
					this.setData({
						errorTips: 5
					})
					return
				}
				if (this.comNewPassWord && this.newPassWord && (this.comNewPassWord != this.newPassWord)) {
					this.setData({
						errorTips: 7,
						identical: false
					})
					return
				}

				var params = {
					url: "/user/updatePwd",
					method: "put",
					data: {
						appType: uni.getStorageSync('appType'), // 应用类型
						checkRegisterSmsFlag: this.checkRegisterSmsFlag, // 校验登陆注册验证码成功的标识
						mobile: this.principal,
						password: this.newPassWord,
						validCode: this.validCode,
						validateType: 1 //验证类型 1验证码验证 2 小程序encryptedData验证 3 密码验证
					},
					callBack: res => {
						uni.showToast({
							title: this.i18n.successfullyModified,
							icon: 'none',
							duration: 1500
						})
						setTimeout(() => {
							this.setData({
								isForgetPassword: false
							})

							// 请求退出登陆接口
							http.request({
								url: '/p/logout',
								method: 'GET',
							})
							uni.removeStorageSync('loginResult');
							uni.removeStorageSync('token');
							uni.removeStorageSync('tempToken');
							uni.removeStorageSync('recentSearch');
							uni.removeStorageSync('hadBindUser');
							uni.removeStorageSync('code');
							util.removeTabBadge()
							// 重置uuid、uuidSession、sessionTimeStamp、step、flowAnalysisLogDto
							uni.setStorageSync('uuid', util.getUuid())
							uni.setStorageSync('uuidSession', util.getUuid())
							uni.setStorageSync('sessionTimeStamp', new Date().getTime())
							uni.setStorageSync('step', 0)
							uni.setStorageSync('flowAnalysisLogDto', '')

							// #ifdef H5
							if (uni.getStorageSync('appType') == AppType.MP) {
								http.mpAuthLogin('/packageLogin/pages/accountLogin/accountLogin', true)
							} else {
								uni.redirectTo({
									url: "/packageLogin/pages/accountLogin/accountLogin"
								})
							}
							// #endif
							// #ifdef APP-PLUS
							uni.redirectTo({
								url: "/packageLogin/pages/accountLogin/accountLogin"
							})
							// #endif

						}, 1500);
					},
				};
				http.request(params);
			},

			//返回
			goBack() {
				this.setData({
					principal: '',
					errorTips: '',
					newPassWord: '',
					validCode: '',
					comNewPassWord: '',
					isForgetPassword: false,
					nextBtn: false
				})

				uni.setNavigationBarTitle({
					title: this.i18n.userLogin
				});
			},

			/**
			 * 去注册
			 */
			toRegitser() {
				uni.redirectTo({
					url: "/packageLogin/pages/register/register"
				})
			},

			/**
			 * 回到首页
			 */
			toIndex() {
				this.$Router.pushTab('/pages/index/index')
			},

			/**
			 * 去条款页
			 */
			toTermsOfService(key) {
				uni.navigateTo({
					url: "/packageLogin/pages/termsPage/termsPage?sts=" + key
				})
			}
		}
	};
</script>
<style lang="scss">
	page {
		background: #fff;
		height: 100%;
	}

	.account-login-wrapper {
		margin-top: 50px;
		padding-bottom: 80px;


		.logo {
			display: flex;
			justify-content: center;
			height: 150rpx;
			margin-bottom: 8%;
			object-fit: contain;

			image {
				display: block;
				width: 100%;
				height: 100%;
			}
		}

		.login-form {
			width: 90%;
			margin: 0 auto;
			margin-bottom: 20%;

			.form-title {
				margin-bottom: 50rpx;
				width: 100%;
				font-size: 32rpx;
				text-align: center;
				color: #00a0e9;
			}

			.item {
				display: block;
				margin-bottom: 40rpx;

				.account {
					display: flex;
					align-items: center;
					padding: 22rpx 16rpx;
					background: #f8f8f8;
					box-sizing: border-box;
					font-size: 26rpx;

					.input-item {
						font-size: 30rpx;
					}

					input {
						padding-left: 20rpx;
						width: 75%;
					}

					.inp-palcehoder {
						font-size: 26rpx;
					}

					input.int-yzm {
						padding-right: 10rpx;
						width: 396rpx;
						box-sizing: border-box;
					}

					.input-btn {
						width: 152rpx;
						font-size: 26rpx;
						color: #00a0ea;
						text-align: center;
					}

					button::after {
						border: 0 !important;
					}
				}
			}

			/* 找回密码&去注册 */
			.operate {
				display: flex;
				justify-content: space-between;
				align-items: center;


				.forgot-password,
				.to-register {
					font-size: 30rpx;
					color: #00AAFF;
				}

				.forgot-passwordEn,
				.to-registerEn {
					font-size: 30rpx;
					color: #00AAFF;
				}

				.forgot-passwordEn {
					flex: 3
				}

				.to-registerEn {
					flex: 2
				}
			}

			/* 错误提示 */
			.error {
				.error-text {
					display: block;
					margin-top: 10rpx;
					width: 100%;
					font-size: 28rpx;
					color: #e43130;
					text-align: left;

					.warning-icon {
						display: inline-block;
						margin-right: 12rpx;
						width: 26rpx;
						height: 26rpx;
						line-height: 26rpx;
						color: #fff;
						background: #e43130;
						border-radius: 50%;
						text-align: center;
						font-size: 22rpx;
					}
				}
			}

			/* 条款声明 */
			.statement {
				font-size: 12px;
				line-height: 2em;

				.statement-text {
					margin-left: 3px;
				}

				.statement-text text {
					color: #00AAFF;
					cursor: pointer;
				}
			}
		}

		.authorized-btn {
			margin: 0 auto;
			padding: 10rpx 0;
			margin-top: 80rpx;
			width: 90%;
			text-align: center;
			background-color: #0ab906;
			border: 1rpx solid #0ab906;
			color: #fff;
			border-radius: 6rpx;
			font-size: 30rpx;
		}

		.to-idx-btn {
			margin: 0 auto;
			padding: 10rpx 0;
			margin-top: 30rpx;
			width: 90%;
			text-align: center;
			background-color: #eeeeee;
			color: #333;
			border-radius: 6rpx;
			font-size: 30rpx;
		}
	.choose .uni-label-pointer{
		width:100% !important;
	}
	}
</style>
